package com.example.toycarcontroller.base

import android.app.Activity
import android.os.Build // 添加缺失的导入
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

/**
 * ViewBinding工具类，简化Activity、Fragment和ViewGroup中的ViewBinding初始化
 */

// ====== Fragment ViewBinding 委托 ======
fun <VB : ViewBinding> Fragment.viewBinding(viewBinder: (View) -> VB)
        : ReadOnlyProperty<Fragment, VB> = FragmentViewBindingProperty(viewBinder)

class FragmentViewBindingProperty<VB : ViewBinding>(
    private val viewBinder: (View) -> VB
) : ReadOnlyProperty<Fragment, VB> {

    private var binding: VB? = null

    override fun getValue(thisRef: Fragment, property: KProperty<*>): VB {
        return binding ?: run {
            thisRef.viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    super.onDestroy(owner)
                    Log.d("ViewBinding", "Clearing binding for ${thisRef::class.java.simpleName}")
                    Handler(Looper.getMainLooper()).post { binding = null }
                    owner.lifecycle.removeObserver(this)
                }
            })
            val view = thisRef.requireView()
            viewBinder(view).also { binding = it }
        }
    }
}

// ====== Activity ViewBinding 委托 (修复版) ======
fun <VB : ViewBinding> Activity.viewBinding(
    viewInflater: (LayoutInflater) -> VB
): ReadOnlyProperty<Activity, VB> = ActivityViewBindingProperty(viewInflater)

class ActivityViewBindingProperty<VB : ViewBinding>(
    private val viewInflater: (LayoutInflater) -> VB
) : ReadOnlyProperty<Activity, VB> {

    private var binding: VB? = null

    override fun getValue(thisRef: Activity, property: KProperty<*>): VB {
        return binding ?: viewInflater(thisRef.layoutInflater).also { vb ->
            thisRef.setContentView(vb.root)
            binding = vb

            // 添加安全生命周期检测
            if (thisRef is LifecycleOwner) {
                thisRef.lifecycle.addObserver(object : DefaultLifecycleObserver {
                    override fun onDestroy(owner: LifecycleOwner) {
                        Log.d("ViewBinding", "Clearing binding for ${thisRef::class.java.simpleName}")
                        binding = null
                        owner.lifecycle.removeObserver(this)
                    }
                })
            } else {
                // 非生命周期感知Activity的回退方案
                Handler(Looper.getMainLooper()).postDelayed({
                    if (thisRef.isDestroyedCompat()) {
                        Log.d("ViewBinding", "Clearing binding for ${thisRef::class.java.simpleName} (fallback)")
                        binding = null
                    }
                }, 1000)
            }
        }
    }
}

// 普通Activity的销毁状态检查扩展
private fun Activity.isDestroyedCompat(): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        isDestroyed
    } else {
        @Suppress("DEPRECATION")
        isFinishing
    }
}

// ====== ViewGroup ViewBinding 委托 (修复版) ======
fun <VB : ViewBinding> ViewGroup.viewBinding(
    @LayoutRes layoutRes: Int,
    viewBinder: (View) -> VB
): ReadOnlyProperty<ViewGroup, VB> = ViewGroupBindingProperty(layoutRes, viewBinder)

class ViewGroupBindingProperty<VB : ViewBinding>(
    @LayoutRes private val layoutRes: Int,
    private val viewBinder: (View) -> VB
) : ReadOnlyProperty<ViewGroup, VB> {

    private var binding: VB? = null

    override fun getValue(thisRef: ViewGroup, property: KProperty<*>): VB {
        return binding ?: run {
            val view = LayoutInflater.from(thisRef.context).inflate(layoutRes, thisRef, false)
            viewBinder(view).also {
                thisRef.addView(view)  // 自动添加到父布局
                binding = it

                // 添加ViewGroup销毁监听
                thisRef.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
                    override fun onViewAttachedToWindow(v: View) {}
                    override fun onViewDetachedFromWindow(v: View) {
                        Log.d("ViewBinding", "Clearing binding for ${thisRef::class.java.simpleName} (detached)")
                        binding = null
                        v.removeOnAttachStateChangeListener(this)
                    }
                })
            }
        }
    }
}
